package com.zhouyu.user.service;

import com.zhouyu.springframework.BeanPostProcessor;
import com.zhouyu.springframework.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Author 韩诚
 * @Date 2024/5/6 17:44
 */
@Component
public class WeiXiaoBeanPostProcessor implements BeanPostProcessor {
    /**
     * 初始化前
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化前：bean的名称 ：" + beanName + "；bean对象：" + bean);
        return bean;
    }

    /**
     * 初始化后
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //只有userService类执行aop逻辑
        if (beanName.equals("userService")) {
            Object proxyInstance = Proxy.newProxyInstance(WeiXiaoBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler(){
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //切面逻辑
                    System.out.println("执行切面逻辑，比如事务开启，等等");

                    //此处传的是bean对象，原始对象，不是代理对象proxy
                    return method.invoke(bean, args);
                }
            });
            System.out.println("初始化后，已被aop：bean的名称 ：" + beanName + "；bean对象：" + proxyInstance);
            return proxyInstance;
        }

        //其他类不执行aop
        System.out.println("初始化后，没有进行aop：bean的名称 ：" + beanName + "；bean对象：" + bean);
        return bean;
    }
}
